// HelloWin.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "HelloWin.h"

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE hInst;								// current instance
TCHAR szTitle[MAX_LOADSTRING];					// The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];			// the main window class name

// Forward declarations of functions included in this code module:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	About(HWND, UINT, WPARAM, LPARAM);
BOOL				SetupOpenGL(HDC);
VOID				OutputMatrix(GLdouble*matrix);
void	Render();
HWND	g_hWnd		= NULL;
HDC		g_hDC		= NULL;

VOID OutputMatrix(GLenum genum) 
{
	double matrix[16] = {0};
	glGetDoublev(genum, matrix);
	OutputMatrix(matrix);
};
VOID OutputMatrix(GLdouble* matrix)
{
	int count = 16;
	printf("\n");
	for (int i = 0; i < count; ++i) {
		printf("%f\t", matrix[i]);
		if ((i + 1) % 4 == 0) {
			printf("\n");
		} 
	}
}

int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPTSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

 	// TODO: Place code here.
	MSG msg;
	HACCEL hAccelTable;

	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_HELLOWIN, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_HELLOWIN));

	bool done = false;   //initialize loop condition variable

	while (!done)
	{
		PeekMessage(&msg, g_hWnd, NULL, NULL, PM_REMOVE);

		if (msg.message == WM_QUIT)     //did we receive a quit message?
		{
			done = true;
		}

		else
		{
			Render();
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}


	return (int) msg.wParam;
}

//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_HELLOWIN));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= MAKEINTRESOURCE(IDC_HELLOWIN);
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   hInst = hInstance; // Store instance handle in our global variable

   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   g_hWnd = hWnd;

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	static BOOL bOpenGLInit = false;
	static HGLRC hglrc = NULL;
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_CREATE:
		{
#ifdef _DEBUG
			AllocConsole();
			FILE* fp;
			freopen_s(&fp, "CONOUT$", "w", stdout);
#endif
			hdc = GetDC(hWnd);
			g_hDC = hdc;
			if (!hdc) {
				assert(false);
				return 0;
			}
			bOpenGLInit = SetupOpenGL(hdc);
			if (!bOpenGLInit) {
				assert(false);
				return 0;
			}
			hglrc = wglCreateContext(hdc);
			if (!hglrc) {
				assert(false);
				return 0;
			}
			wglMakeCurrent(hdc, hglrc);
			return 0;
		}
	case WM_DESTROY: 
		{
			hdc = GetDC(hWnd);
			wglMakeCurrent(hdc, NULL);
			wglDeleteContext(hglrc);
			ReleaseDC(hWnd, hdc);
			PostQuitMessage(0);
			exit(-1);
			break;
		}
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	switch (message)
	{
	case WM_INITDIALOG:
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return (INT_PTR)TRUE;
		}
		break;
	}
	return (INT_PTR)FALSE;
}

BOOL SetupOpenGL(HDC hdc)
{
	PIXELFORMATDESCRIPTOR pfd = { 
		sizeof(PIXELFORMATDESCRIPTOR),    // size of this pfd  
		1,                                // version number  
		PFD_DRAW_TO_WINDOW |              // support window  
		PFD_SUPPORT_OPENGL |              // support OpenGL  
		PFD_DOUBLEBUFFER,                 // double buffered  
		PFD_TYPE_RGBA,                    // RGBA type  
		24,                               // 24-bit color depth  
		0, 0, 0, 0, 0, 0,                 // color bits ignored  
		0,                                // no alpha buffer  
		0,                                // shift bit ignored  
		0,                                // no accumulation buffer  
		0, 0, 0, 0,                       // accum bits ignored  
		32,                               // 32-bit z-buffer      
		0,                                // no stencil buffer  
		0,                                // no auxiliary buffer  
		PFD_MAIN_PLANE,                   // main layer  
		0,                                // reserved  
		0, 0, 0                           // layer masks ignored  
	}; 
	int  iPixelFormat; 

	// get the device context's best, available pixel format match  
	iPixelFormat = ChoosePixelFormat(hdc, &pfd); 
	if (!iPixelFormat) {
		return FALSE;
	}

	// make that match the device context's current pixel format  
	if (!SetPixelFormat(hdc, iPixelFormat, &pfd)){
		return FALSE;
	}
	return TRUE;
}

void Render()
{
	RECT rect;
	GetClientRect(g_hWnd, &rect);
	
	glClearColor(0xff, 0xff, 0xff, 0xff);
	glClear( GL_COLOR_BUFFER_BIT );
	glColor3f(0xff, 0x00 , 0x00);

	glMatrixMode(GL_PROJECTION_MATRIX);
	gluOrtho2D(-1, 0.3, 0.3, -1);

	glViewport(0, 0, rect.right - rect.left, rect.bottom - rect.top );
	
	glMatrixMode(GL_MODELVIEW_MATRIX);
	glLoadIdentity();

	//glTranslated(-1, -1, 0);
	//front polygon
	glBegin(GL_POLYGON);
		glColor3f(0xff, 0x00, 0x00);
		glVertex3f(0, 0, 0);
		glVertex3f(0.5, 0, 0);
		glVertex3f(0.5, 0.5, 0);
		glVertex3f(0, 0.5, 0);
	glEnd();

	//back polygon
	glBegin(GL_POLYGON);
		glColor3f(0xff, 0x00, 0x00);
		glVertex3f(0, 0, -0.5);
		glVertex3f(0.5, 0, -0.5);
		glVertex3f(0.5, 0.5, -0.5);
		glVertex3f(0, 0.5, -0.5);
	glEnd();

	//top polygon
	glBegin(GL_POLYGON);
		glColor3f(0xff, 0x00, 0x00);
		glVertex3f(0, 0.5, 0);
		glVertex3f(0.5, 0.5, 0);
		glVertex3f(0.5, 0.5, -0.5);
		glVertex3f(0, 0.5, -0.5);
	glEnd();

	//bottom polygon
	glBegin(GL_POLYGON);
		glColor3f(0xff, 0x00, 0x00);
		glVertex3f(0, 0, 0);
		glVertex3f(0.5, 0, 0);
		glVertex3f(0.5, 0, -0.5);
		glVertex3f(0, 0, -0.5);
	glEnd();

	//left polygon
	glBegin(GL_POLYGON);
		glColor3f(0xff, 0x00, 0x00);
		glVertex3f(0, 0, 0);
		glVertex3f(0, 0, -0.5);
		glVertex3f(0, 0.5, -0.5);
		glVertex3f(0, 0.5, 0);
	glEnd();

	//right polygon
	glBegin(GL_POLYGON);
		glColor3f(0xff, 0x00, 0x00);
		glVertex3f(0.5, 0, 0);
		glVertex3f(0.5, 0, -0.5);
		glVertex3f(0.5, 0.5, -0.5);
		glVertex3f(0.5, 0.5, 0);
	glEnd();

	//glPopMatrix();
	SwapBuffers( g_hDC );
}